const Koa = require('koa')
const cors = require('koa-cors')
const bodyparser = require('koa-bodyparser')
const router = require('koa-router')()
const { Sequelize, DataTypes, Op } = require('sequelize')
const { parseInt } = require('lodash')

const app = new Koa()
const sequelize = new Sequelize('demo01', 'sa', '123456', {
    host: 'localhost',
    dialect: 'mssql'
})

sequelize.authenticate().then(() => {
    try {
        console.log('成功');
    } catch (error) {
        console.log('失败');
    }
})

let StuClass = sequelize.define('StuClass', {
    name: {
        type: DataTypes.STRING,
        allowNull: false
    }
})

let Student = sequelize.define('Student', {
    name: {
        type: DataTypes.STRING,
        allowNull: false
    },
    age: {
        type: DataTypes.INTEGER,
        allowNull: true
    },
    classId: {
        type: DataTypes.INTEGER,
        allowNull: false
    },
})

// sequelize.sync({force:true}).then(async()=>{
//     let sclass = await StuClass.create(
//         {name: '1班'}
//     )

//     await Student.bulkCreate([
//         {
//             name: "张三",
//             age: 13,
//             classId: 1
//         },
//         {
//             name: "里斯",
//             age: 43,
//             classId: 1
//         },
//     ])
// })
app.use(cors())
app.use(bodyparser())

router.get('/student', async (ctx) => {
    let keyword = ctx.request.query.keyword || ''

    let pageIndex = parseInt(ctx.request.query.pageIndex) || 1
    let pageSize = parseInt(ctx.request.query.pageSize) || 5

    console.log(pageIndex);
    console.log(pageSize);
    let sclass = await StuClass.findAll()
    let arr = []
    if (keyword && keyword.length > 0 && !pageIndex) {
        const data = await Student.findAll({
            where: {
                [Op.or]: [
                    { id: isNaN(keyword) ? 0 : parseInt(keyword) },
                    { name: keyword },
                    { age: isNaN(keyword) ? 0 : parseInt(keyword) }
                ]
            },
            order: ['id']
        })

        data.forEach(item => {
            let list = sclass.find(obj => {
                return obj.id === item.classId
            })
            item.dataValues.className = list.dataValues.name
            arr.push(item)
        })
    } else {
        console.log(pageIndex);
        const { count, rows } = await Student.findAndCountAll({
            offset: (pageIndex - 1) * pageSize,
            limit: pageSize
        })
        rows.forEach(item => {
            let list = sclass.find(obj => {
                return obj.id === item.classId
            })
            item.dataValues.className = list.dataValues.name
            arr.push(item)
        })
    }
    ctx.body = {
        code: 1,
        msg: "查询成功",
        data: arr
    }
}).post('/student', async (ctx) => {
    let obj = ctx.request.body

    let data = await Student.create(obj)
    ctx.body = {
        code: 2,
        msg: "新增成功",
        data: data
    }
}).put('/stuent/:id', async (ctx) => {
    let id = ctx.request.params.id
    let obj = ctx.request.body

    let data = await Student.update(obj, {
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 4,
        msg: "修改成功",
        data: data
    }

}).delete('/student/:id', async (ctx) => {
    let id = ctx.request.params.id
    console.log(id);
    let data = await Student.destroy({
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 5,
        msg: "删除成功",
        data: data
    }
}).get('/student/:id', async (ctx) => {
    let id = ctx.request.params.id
    let data = await Student.findAll({
        where: {
            id: id
        }
    })
    ctx.body = {
        code: 6,
        msg: "查找成功",
        data: data
    }
})

app.use(router.routes())

app.listen(3000, () => {
    console.log('http://localhost:3000');
})